use std::{slice::{Iter, IterMut}, iter::Rev};

use super::layer::Layer;

#[derive(Default)]
pub struct LayerStack {
    records: Vec<Box<dyn Layer>>,
    record_pos: usize,
}

impl LayerStack {
    pub fn push_layer(&mut self, mut layer: Box<dyn Layer>) {
        layer.attach();
        self.records.insert(self.record_pos, layer);
        self.record_pos += 1;
    }

    pub fn push_over_layer(&mut self, mut layer: Box<dyn Layer>) {
        layer.attach();
        self.records.push(layer);
    }

    pub fn pop_layer(&mut self, layer: &Box<dyn Layer>) {
        if let Some((index, _)) = self
            .records
            .iter()
            .enumerate()
            .find(|(_, r)| r.get_name() == layer.get_name())
        {
            let mut target = self.records.remove(index);
            target.detach();
        }
    }

    pub fn pop_over_layer(&mut self, layer: &Box<dyn Layer>) {
        if let Some((index, _)) = self
            .records
            .iter()
            .enumerate()
            .find(|(_, r)| r.get_name() == layer.get_name())
        {
            let mut target = self.records.remove(index);
            target.detach();
            self.record_pos -= 1;
        }
    }

    pub fn iter(&self) -> Iter<'_, Box<dyn Layer>> {
        self.records.iter()
    }

    pub fn iter_mut(&mut self) -> IterMut<'_, Box<dyn Layer>> {
        self.records.iter_mut()
    }

    pub fn iter_rev(&self) -> Rev<Iter<'_, Box<dyn Layer>>> {
        self.records.iter().rev()
    }

    pub fn iter_mut_rev(&mut self) -> Rev<IterMut<'_, Box<dyn Layer>>> {
        self.records.iter_mut().rev()
    }

}
